from datetime import datetime

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from database.config import get_db
from models.model import *
from models.base import *
from utils.deps import verify_token


router = APIRouter()

# 用户板
@router.get("/user_board")
async def get_user_board(
        currentUser: dict = Depends(verify_token),
        db: Session = Depends(get_db)):
    username = currentUser["username"]
    user = db.query(User).filter(User.username == username).first()
    res_data = {"intention_position",user.position}
    return Success(code = 200, msg = "success", res_data = res_data)

# 学习资源右上侧岗位技能视频
@router.get("/position_video")
async def get_position_video(db: Session = Depends(get_db)):
    skill_video_list = db.query(Video).filter(Video.video_type == 0).all()
    res_data = {"skill_video_list":skill_video_list}
    return Success(code = 200, msg = "success", res_data = res_data)

# 学习资源右下侧面试技巧视频
@router.get("/interview_video")
async def get_interview_video(db: Session = Depends(get_db)):
    interview_video_list = db.query(Video).filter(Video.video_type == 1).all()
    res_data = {"interview_video_list": interview_video_list}
    return Success(code=200, msg="success", res_data=res_data)

# 视频详情页
@router.get("/video/{video_id}")
async def get_video_details(video_id : str,
                            currentUser: dict = Depends(verify_token),
                            db: Session = Depends(get_db)):
    username = currentUser["username"]
    # 添加视频浏览记录
    new_learn_history = LearnHistory(username = username, video_id = video_id, watch_history_time=datetime.now())
    db.add(new_learn_history)
    db.commit()
    db.refresh(new_learn_history)

    # 获取视频详情页
    video = db.query(Video).filter(Video.video_id == video_id).first()
    video_url = video.video_url
    video_uploader = video.video_author
    video_publish_time = video.video_publish_time
    video_info = {
        "video_uploader": video_uploader,
        "video_publish_time": video_publish_time.strftime("%Y-%m-%d")
    }

    # 视频评论
    video_comment_list = []
    commentList = db.query(VideoComment).filter(VideoComment.video_id == video_id).all()
    for comment in commentList:
        video_comment = {
            "comment_id": comment.comment_id,
            "comment_author": comment.comment_author,
            "comment_author_avatar": comment.comment_author_avatar,
            "comment_time": comment.comment_time.strftime("%Y-%m-%d"),
            "comment_content": comment.comment_content,
            "comment_like_num": comment.comment_like_num,
            "comment_dislike_num": comment.comment_dislike_num,
        }
        video_comment_list.append(video_comment)

    # 相关视频
    related_video_list = []
    related_video_id = db.query(RelatedVideo).filter(RelatedVideo.video_id == video_id).all()
    for related_video in related_video_id:
        id = related_video.related_id
        video = db.query(Video).filter(Video.video_id == id).first()
        related_video_list.append({
            "video_name": video.video_name,
            "video_id": video.video_id,
            "video_author": video.video_author,
            "video_publish_time": video.video_publish_time.strftime("%Y-%m-%d"),
            "video_pic": video.video_pic
        })
    res_data = {
        "video_url": video_url,
        "video_info": video_info,
        "video_comment_list": video_comment_list,
        "related_video_list": related_video_list
    }
    return Success(code=200, msg="success", res_data=res_data)

# 面试题详情页
@router.get("/question/{question_id}")
async def get_question_details(question_id : str, db: Session = Depends(get_db)):
    question = db.query(QuestionBank).filter(QuestionBank.question_id == question_id).first()

    # 问题评论表
    quetsion_comment_list = []
    commentList = db.query(QuetsionComment).filter(QuetsionComment.question_id == question_id).all()
    for comment in commentList:
        quetsion_comment_list.append({
            "comment_id": comment.comment_id,
            "comment_author": comment.comment_author,
            "comment_author_avatar": comment.comment_author_avatar,
            "comment_time": comment.comment_time.strftime("%Y-%m-%d"),
            "comment_content": comment.comment_content,
            "comment_like_num": comment.comment_like_num,
            "comment_dislike_num": comment.comment_dislike_num
        })

    # 相关问题列表
    tag_map = {}
    # related_question_list = []
    related_question_ids = db.query(RelatedQuestion).filter(RelatedQuestion.question_id == question_id).all()
    for related_question_id in related_question_ids:
        id = related_question_id.related_id
        related_question = db.query(QuestionBank).filter(QuestionBank.question_id == id).first()
        tag = related_question.tag

        # 加入对应 tag 的列表中
        if tag not in tag_map:
            tag_map[tag] = []
        tag_map[tag].append(related_question)
        # found = False
        # for group in related_question_list:
        #     if group["tag"] == tag:
        #         group["question_list"].append(related_question)
        #         found = True
        #         break
        # if not found:
        #     related_question_list.append({
        #         "tag": tag,
        #         "question_list": [related_question]
        #     })

    # 转换成最终所需格式的列表
    related_question_list = [
        {
            "tag": tag,
            "question_list": question_list
        }
        for tag, question_list in tag_map.items()
    ]

    res_data = {
        "question_id": question.question_id,
        "question_number": question.question_number,
        "question_title": question.question_title,
        "question_answer_content": question.question_answer_content,
        "tag": question.tag,
        "quetsion_comment_list": quetsion_comment_list,
        "related_question_list": related_question_list,
    }

    return Success(code=200, msg="success", res_data=res_data)

# 面试题库
@router.get("/question_list")
async def get_question_list(db: Session = Depends(get_db)):
    # 基础技术 0
    basic_tag_map = {}
    basic_questions = db.query(QuestionBank).filter(QuestionBank.type == 0)
    for basic_question in basic_questions:
        tag = basic_question.tag
        if tag not in basic_tag_map:
            basic_tag_map[tag] = []
        basic_tag_map[tag].append(basic_question)
    basic_tech_list = [
        {
            "tag": tag,
            "question_list": question_list
        }
        for tag, question_list in basic_tag_map.items()
    ]

    # 项目经历 1
    project_tag_map = {}
    project_questions = db.query(QuestionBank).filter(QuestionBank.type == 1)
    for project_question in project_questions:
        tag = project_question.tag
        if tag not in project_tag_map:
            project_tag_map[tag] = []
        project_tag_map[tag].append(project_question)
    project_experience_list = [
        {
            "tag": tag,
            "question_list": question_list
        }
        for tag, question_list in project_tag_map.items()
    ]

    # 职业规划 2
    career_plan_list = []
    carrer_tag_map = {}
    carrer_questions = db.query(QuestionBank).filter(QuestionBank.type == 2)
    for carrer_question in carrer_questions:
        tag = carrer_question.tag
        if tag not in carrer_tag_map:
            carrer_tag_map[tag] = []
        carrer_tag_map[tag].append(carrer_question)
    career_plan_list = [
        {
            "tag": tag,
            "question_list": question_list
        }
        for tag, question_list in carrer_tag_map.items()
    ]

    # 行业动态 3
    industy_tag_map = {}
    industry_questions = db.query(QuestionBank).filter(QuestionBank.type == 3)
    for industry_question in industry_questions:
        tag = industry_question.tag
        if tag not in industy_tag_map:
            industy_tag_map[tag] = []
        industy_tag_map[tag].append(industry_question)
    industry_dynamic_list = [
        {
            "tag": tag,
            "question_list": question_list
        }
        for tag, question_list in industy_tag_map.items()
    ]

    res_data = {
        "basic_tech_list": basic_tech_list,
        "project_experience_list": project_experience_list,
        "career_plan_list": career_plan_list,
        "industry_dynamic_list": industry_dynamic_list
    }
    return Success(code=200, msg="success", res_data=res_data)